package secondkill.Exception;

import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import secondkill.vo.RespBean;
import secondkill.vo.RespBeanEnum;

/**
 * 全局异常处理类
 * @Auther  丁子川
 * @create 2022/1/14 18:06
 */
//@ControllerAdvice：异常集中处理，更好的使业务逻辑与异常处理剥离开；其是对Controller层进行拦截
@RestControllerAdvice
public class GlobalExceptionHandler{
    //@ExceptionHandler：统一处理某一类异常，从而能够减少代码重复率和复杂度
    @ExceptionHandler(Exception.class)
    public RespBean ExceptionHandler(Exception e) {
        if (e instanceof GlobalException) {
            //将异常转为全局异常
            GlobalException ex = (GlobalException) e;
            return RespBean.error(ex.getRespBeanEnum());
        } else if (e instanceof BindException) {
            //将特定的绑定异常拎出进行强转
            BindException ex = (BindException) e;
            RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
            respBean.setMessage("PARAMETER CHECK ERROR: " + ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }
}
